﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Atmk.WaterMeter.MIS.Commons.ViewModels.District;
using Atmk.WaterMeter.MIS.TestForm.Common;
using Atmk.WaterMeter.MIS.TestForm.Views.DataMock.Helper;
using Atmk.WaterMeter.MIS.TestForm.Views.DataMock.vo;
using Common.Logging;
using Newtonsoft.Json;
using NKnife.IoC;
using RestSharp;

namespace Atmk.WaterMeter.MIS.TestForm.Views
{
    public partial class AddDistrict : Form
    {
        private static readonly ILog _Logger = LogManager.GetLogger<AddDistrict>();
        private readonly CurrentMock _current;

        private readonly Kernel _kernel;

        public AddDistrict(DistrictNode node,string projectId)
        {
            _kernel = DI.Get<Kernel>();
            _current = DI.Get<CurrentMock>();
            InitializeComponent();
            _ParentId.Text = node.id;
            _projectId.Text = projectId;

        }

        private void _Add_Click(object sender, EventArgs e)
        {
            var request = new RestRequest(UrlManager.InsertDistricts, Method.POST);
            request.AddHeader("X-Token", _kernel.Token);

            var name = _DistrictNameText.Text;
            var d = new district(_projectId.Text, string.Empty, name,string.Empty,_ParentId.Text);
            request.AddJsonBody(d);
            _kernel.Client.ExecuteAsync(request, response =>
            {
                var data = response.Content;
                _Logger.Trace(data);
                try
                {
                    var districtReturn = JsonConvert.DeserializeObject<BaseAddResult>(data);
                    var districtId = districtReturn.id;
                    _current.SaveDistrict(districtId, name);
                    Invoke((EventHandler)delegate {
                        Close();
                    });
                }
                catch (Exception exception)
                {
                    _Logger.Error(exception);
                }
                _Logger.Trace($"{d.ToString()}创建成功");

            });
        }
    }
}
